﻿using System;
using System.Configuration;
using System.Threading;
using log4net;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.BLL.BllExt;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Enum;

namespace Matrix.MaKaYunShang.MaKaYunShangService.MaKaYunShangProccess
{
    /// <summary>
    /// 订单消息服务线程
    /// </summary>
    public class OrderThreadMgr
    {
        public Thread AssignNewOrderThread;
        public Thread ExpiredFinishThread;
        public Thread ExpiredPaidThread;

        public bool BRunning;

        private bool _bExpiredFinishThreadRunning;
        private bool _bNewOrderMsgThreadRunning;
        private bool _bExpiredPaidThreadRunning;

        private bool _bExcuteExpiredFinishOnce;
        private bool _bExcutePaidFinishOnce;

        private int _nThreadInterval;
        private DateTime _dtSysConfigRead;

        private readonly ILog _fileLog = LogManager.GetLogger(typeof(OrderThreadMgr));

        private readonly OrderExtBll _orderExtBll = new OrderExtBll();
        private readonly SysConfigBLL _sysConfigBll = new SysConfigBLL();
        private SysConfig _sysConfigInfo = new SysConfig();

        public OrderThreadMgr(bool running)
        {
            InitialParameters(running);
        }

        /// <summary>
        /// 初始化参数
        /// </summary>
        /// <param name="running"></param>
        private void InitialParameters(bool running)
        {
            _nThreadInterval = int.Parse(ConfigurationManager.AppSettings["ThreadInterval"]);
            BRunning = running;
             _bExpiredFinishThreadRunning = running;
            _bNewOrderMsgThreadRunning = running;
            _bExpiredPaidThreadRunning = running;

            _bExcuteExpiredFinishOnce = false;
            _bExcutePaidFinishOnce = false;

            _dtSysConfigRead = DateTime.Now;
            GetCurrentSysConfig();
        }

        /// <summary>
        /// 创建线程
        /// </summary>
        public void CreateOrderThreads()
        {
            NewOrderMsgThread();
            ExpiredPaidOrderThread();
            ExpiredFinishOrderThread();
        }

        /// <summary>
        /// 启动线程
        /// </summary>
        public void StartThreads()
        {
            AssignNewOrderThread.Start();
            ExpiredFinishThread.Start();
            ExpiredPaidThread.Start();

            BRunning = true;

            _bExpiredFinishThreadRunning = true;
            _bNewOrderMsgThreadRunning = true;
            _bExpiredPaidThreadRunning = true;
        }

        /// <summary>
        /// 停止线程
        /// </summary>
        public void StopThreads()
        {
            BRunning = false;
        }

        #region 过期未完成订单处理线程

        public void ExpiredFinishOrderThread()
        {
            ExpiredFinishThread = new Thread(ExpiredFinishThreadMain) { IsBackground = true };
        }

        private void ExpiredFinishThreadMain()
        {
            _fileLog.Info("OrderThreadMgr | ExpiredFinishThreadMain : Time - " +
                                  DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  Entry");
            try
            {
                var nExcuteIndex = 0;
                while (_bExpiredFinishThreadRunning)
                {
                    _fileLog.Info("OrderThreadMgr | ExpiredFinishThreadMain : Time - " +
                                  DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " nExcuteIndex：" + nExcuteIndex);
                    nExcuteIndex++;

                    if (_sysConfigInfo == null)
                    {
                        GetCurrentSysConfig();
                        if (_sysConfigInfo == null)
                        {
                            Thread.Sleep(1000);
                            continue;
                        }
                    }
                    else
                    {
                        var tsSysRead = DateTime.Now - _dtSysConfigRead;
                        if (tsSysRead.Minutes >= 10)
                        {
                            GetCurrentSysConfig();
                            if (_sysConfigInfo == null)
                            {
                                Thread.Sleep(1000);
                                continue;
                            }
                        }
                    }

                    var nRet = _orderExtBll.UpdateExpiredOrdersForService(CommonEnum.ServiceOrderQueryType.ExpiredToFinish,
                        _sysConfigInfo);

                    _fileLog.Info("OrderThreadMgr | ExpiredFinishThreadMain : Time - " +
                                  DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ------- 执行记录数：" + nRet + "------------");

                    _bExcuteExpiredFinishOnce = true;
                    if (!BRunning)
                    {
                        _bExpiredFinishThreadRunning = false;
                        break;
                    }
                    Thread.Sleep(_nThreadInterval);
                }
            }
            catch (Exception ex)
            {
                _fileLog.Error("OrderThreadMgr | ExpiredFinishThreadMain : Exception - " + ex.Message + ex.StackTrace);
            }
            _bExcuteExpiredFinishOnce = false;
            _bExpiredFinishThreadRunning = false;
        }
        #endregion

        #region 过期未支付订单处理线程

        public void ExpiredPaidOrderThread()
        {
            ExpiredPaidThread = new Thread(ExpiredPaidThreadMain) { IsBackground = true };
        }

        private void ExpiredPaidThreadMain()
        {
            _fileLog.Info("OrderThreadMgr | ExpiredPaidThreadMain : Time - " +
                                  DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  Entry");

            try
            {
                var nExcuteIndex = 0;
                while (_bExpiredPaidThreadRunning)
                {
                    _fileLog.Info("OrderThreadMgr | ExpiredPaidThreadMain : Time - " +
                                 DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " nExcuteIndex：" + nExcuteIndex);
                    nExcuteIndex++;

                    if (_sysConfigInfo == null)
                    {
                        GetCurrentSysConfig();
                        if (_sysConfigInfo == null)
                        {
                            Thread.Sleep(1000);
                            continue;
                        }
                    }
                    else
                    {
                        var tsSysRead = DateTime.Now - _dtSysConfigRead;
                        if (tsSysRead.Minutes >= 10)
                        {
                            GetCurrentSysConfig();
                            if (_sysConfigInfo == null)
                            {
                                Thread.Sleep(1000);
                                continue;
                            }
                        }
                    }

                    var nRet = _orderExtBll.UpdateExpiredOrdersForService(CommonEnum.ServiceOrderQueryType.ExpiredToPay,
                        _sysConfigInfo);



                    _fileLog.Info("OrderThreadMgr | ExpiredPaidThreadMain : Time - " +
                                  DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ------- 执行记录数：" + nRet + "------------");

                    _bExcutePaidFinishOnce = true;
                    if (!BRunning)
                    {
                        _bExpiredPaidThreadRunning = false;
                        break;
                    }

                    Thread.Sleep(_nThreadInterval);
                }
            }
            catch (Exception ex)
            {
                _fileLog.Error("OrderThreadMgr | ExpiredPaidThreadMain : Exception - " + ex.Message + ex.StackTrace);
            }
            _bExcutePaidFinishOnce = false;
            _bExpiredPaidThreadRunning = false;
        }
        #endregion

        #region 需派送订单消息处理线程
        public void NewOrderMsgThread()
        {
            AssignNewOrderThread = new Thread(NewOrderMsgThreadMain) { IsBackground = true };
        }

        public void NewOrderMsgThreadMain()
        {
            _fileLog.Info("OrderThreadMgr | NewOrderMsgThreadMain : Time - " +
                                  DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  Entry");

            try
            {
                var nExcuteIndex = 0;
                while (_bNewOrderMsgThreadRunning)
                {
                    _fileLog.Info("OrderThreadMgr | NewOrderMsgThreadMain : Time - " +
                                 DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " nExcuteIndex：" + nExcuteIndex);

                    nExcuteIndex++;
                    //干预线程运行，与其他线程时间差异执行
                    if (!_bExcuteExpiredFinishOnce || !_bExcutePaidFinishOnce)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }

                    if (_sysConfigInfo == null)
                    {
                        GetCurrentSysConfig();
                        if (_sysConfigInfo == null)
                        {
                            Thread.Sleep(1000);
                            continue;
                        }
                    }
                    else
                    {
                        var tsSysRead = DateTime.Now - _dtSysConfigRead;
                        if (tsSysRead.Minutes >= 10)
                        {
                            GetCurrentSysConfig();
                            if (_sysConfigInfo == null)
                            {
                                Thread.Sleep(1000);
                                continue;
                            }
                        }
                    }

                    var lsOrders = _orderExtBll.GetUnAssigneOrderInfoForGfcService(_sysConfigInfo);
                    if (lsOrders == null || lsOrders.Count == 0)
                    {
                        if (DateTime.Now.Hour < 6 || DateTime.Now.Hour >= 23)
                        {
                            Thread.Sleep(20000);
                        }
                        else
                        {
                            Thread.Sleep(5000);
                        }
                        
                        continue;
                    }

                    var nSendCount = 1;
                    foreach (var order in lsOrders)
                    {
                        //提交新订单模板消息
                        _orderExtBll.SendNewOrderWxTemplateMsg(order, true);

                        //发送消息到商家后台
                        _orderExtBll.SendMsgToMcManageWeb(order.ShopId, order.OrderNo,
                            order.ConsumerName, CommonEnum.PushingMsgType.AssignRemindOrder);
                        nSendCount ++;
                        if (nSendCount%20 == 0)
                        {
                            Thread.Sleep(1000);
                        }
                    }

                    _fileLog.Info("OrderThreadMgr | NewOrderMsgThreadMain : Time - " +
                                  DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ------- 执行记录数：" + lsOrders.Count + "------------");


                    if (!BRunning)
                    {
                        _bNewOrderMsgThreadRunning = false;
                        break;
                    }
                    Thread.Sleep(_nThreadInterval);
                }
            }
            catch (Exception ex)
            {
                _fileLog.Error("OrderThreadMgr | NewOrderMsgThreadMain : Exception - " + ex.Message + ex.StackTrace);
            }
            _bNewOrderMsgThreadRunning = false;
        }
        #endregion

        /// <summary>
        /// 获取系统配置数据
        /// </summary>
        private void GetCurrentSysConfig()
        {
            try
            {
                var lsSysConfig = _sysConfigBll.GetModelList();
                if (lsSysConfig == null || lsSysConfig.Count == 0 || lsSysConfig[0].Id == 0)
                {
                    _sysConfigInfo = null;
                    return;
                }
                _sysConfigInfo = lsSysConfig[0];
                _dtSysConfigRead = DateTime.Now;
            }
            catch (Exception ex)
            {
                _sysConfigInfo = null;
                _fileLog.Error("OrderThreadMgr | GetCurrentSysConfig : Exception - " + ex.Message + ex.StackTrace);
            }
        }
    }
}
